package com.easybuilder.common.config.interceptor;

import com.alibaba.fastjson.JSONObject;

import com.easybuilder.common.utils.AddressUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Deprecated
//@Component
@Slf4j
public class IPInterceptor implements HandlerInterceptor {

    private static final Map<String, String> urlMap = new HashMap<>();
    @PostConstruct
    public void init(){
        urlMap.put("/", "");
        urlMap.put("/login", "");
        urlMap.put("/login.html", "");
        urlMap.put("/logout", "");
        urlMap.put("/error", "");
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String remoteHost = request.getRemoteHost();
        String remoteAddr = request.getRemoteAddr();
        String requestURI = request.getRequestURI();
        Map<String, String[]> map = request.getParameterMap();
        String params = JSONObject.toJSONString(map);
        log.info("请求地址：" + remoteHost);
        log.info("请求路径: " + requestURI);
        log.info("请求参数: " + JSONObject.toJSONString(params));
        String realAddress = AddressUtils.getRealAddressByIP(remoteHost);
        log.info("真实地址：" + realAddress);
        //token验证
        String authorization = request.getHeader("Authorization");
        Object token = request.getSession().getAttribute("token");
        //Object token2 = request.getServletContext().getAttribute("token");
        //如果当前请求非登陆页面，进行token验证(放过登录页、登陆请求、静态资源、图片映射地址)
        if (urlMap.get(requestURI) == null) { //验证
            //放过静态资源和api(图片映射地址)
            if (requestURI.startsWith("/static") || requestURI.startsWith("/api")) {
                return true;
            }
            if (authorization != null || token != null) {
                return true;
            } else {
                response.getWriter().write("需要认证！");
            }
        } else { //放过
            return true;
        }

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        //System.out.println("拦截器post方法执行");


    }


}
